<template>
  <div ref="chartEl"></div>
</template>
<script lang="ts" setup>
import { use, init, EChartsType } from "echarts/core";
import { TitleComponent, TooltipComponent, GridComponent, LegendComponent } from "echarts/components";
import { BarChart, PieChart, LineChart } from "echarts/charts";
import { LabelLayout } from "echarts/features";
import { CanvasRenderer } from "echarts/renderers";
import type { DefaultSeriesOption, EChartsOption, SeriesOption } from "./models";
import { shallowRef, onMounted, watch, onBeforeUnmount } from "vue";
import { colors } from "/@/style/style";
import { deepMergeObj } from "/@/utils/common";
import ResizeObserver from "resize-observer-polyfill";

const props = defineProps<{
  option?: EChartsOption;
}>();

use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  BarChart,
  PieChart,
  LabelLayout,
  CanvasRenderer,
  LineChart,
]);

const chartEl = shallowRef<HTMLDivElement>();

const defaultSeriesOption: DefaultSeriesOption = {
  bar: {
    barMaxWidth: 30,
  },
};
function handleSeries(option?: SeriesOption): SeriesOption | null {
  if (option && option.type) {
    const target = defaultSeriesOption[option.type];
    if (target) {
      return Object.assign({}, target, option);
    }
  }
  return null;
}
function handleOption(option: EChartsOption) {
  const defaultOption: EChartsOption = {
    legend: {},
    grid: {
      left: 16,
      right: 16,
      bottom: 16,
      top: 16,
      containLabel: true,
    },
  };
  deepMergeObj(defaultOption, option);
  //处理series默认配置
  if (defaultOption.series) {
    if (Array.isArray(defaultOption.series)) {
      defaultOption.series.forEach((el, i, arr) => {
        const re = handleSeries(el);
        if (re) {
          arr[i] = re;
        }
      });
    } else {
      const re = handleSeries(defaultOption.series);
      if (re) {
        defaultOption.series = re;
      }
    }
  }
  return defaultOption;
}

let chartIns: EChartsType | null = null;
let resizeObserver: ResizeObserver | null;
onMounted(() => {
  if (chartEl.value && props.option) {
    chartIns = init(chartEl.value);
    const option = handleOption(props.option);
    chartIns.setOption(option);
  }

  if (chartEl.value) {
    const containerEl = chartEl.value;
    //实现自适应div container的大小
    resizeObserver = new ResizeObserver((entries: ResizeObserverEntry[]) => {
      const entry = entries[0];
      // console.log("========>ResizeObserver resize");
      if (entry && chartIns) {
        chartIns.resize();
      }
    });
    resizeObserver.observe(containerEl);
  }
});
onBeforeUnmount(() => {
  if (resizeObserver) {
    console.log("=======>ResizeObserver unmount");
    resizeObserver.disconnect();
    resizeObserver = null;
  }
});
watch(
  () => props.option,
  (v) => {
    if (chartIns && v) {
      const option = handleOption(v);
      chartIns.setOption(option);
    } else {
      chartIns = null;
    }
  }
);
</script>
